package com.example.handdet;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FaceDetectUtil {
    //private static String face_detect_host = "http://120.27.157.19:11000";
    private static String face_detect_host= "http://aiapi-lt.haiersmarthomes.com:11000";
    private static String face_detect_url = "/ai-access/ir/face/detect";
    public static final String VERSION_NAME = "1.0.0_20210517";
    private static  FaceDetectUtil  instance=null;
    private static String TAG="FaceDetectUtil";
    private static final long _index = 0;
    public static  FaceDetectUtil getInstance(){
        if(instance==null)
            instance=new FaceDetectUtil();
        return instance;
    }
    public OkHttpClient getAuthorizationClient() {
        String timeStamp=String.valueOf(System.currentTimeMillis());
        String timezone = String.valueOf(TimeZone.getDefault().getRawOffset() / (60 * 60 * 1000));
        String sequenceId=timeStamp+"_"+_index;

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request.Builder builder = chain.request()
                                .newBuilder()
                                .addHeader("Content-Type", "application/json;charset=UTF-8")
                                .addHeader("appId",AppConstants.UHOME_APP_ID)
                                .addHeader("appVersion", VERSION_NAME)
                                .addHeader("clientId",AppConstants.UHOME_CLIENT_ID)
                                .addHeader("sequenceId",sequenceId)
                                .addHeader("sign",getSign())
                                .addHeader("timestamp",timeStamp)
                                .addHeader("language","zh-cn")
                                .addHeader("timezone",timezone);
                        Request request = builder.build();
                        Log.d(TAG,"Request = " + request.url());
                        Log.d(TAG,"Request = " + request.headers().toString());
                        Log.d(TAG,"#######################");
                        return chain.proceed(request);
                    }
                })
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();

        return okHttpClient;
    }


    /**
     *  人脸检测
     * */
    public UserResponse face_detect() throws Exception {
        Log.d(TAG,"face detect request in ...");
        UserResponse userResponse=new UserResponse();
        Log.i(TAG,"1111111111111");
        OkHttpClient client = getAuthorizationClient();
        Map<String, Object> requestParam = new HashMap<>();
        Log.i(TAG,"2222222222222222");
        requestParam.put("deviceId", AppConstants.UHOME_DEVICEID);
        requestParam.put("faceData", Base64Util.encodeBase64File(Base64Util.DEFAULT_COMPRESSED_FILE_PATH));
        requestParam.put("width", 640);
        requestParam.put("height", 1080);
        Log.i(TAG,"33333333333333");
        String jsonBody = new JSONObject(requestParam).toJSONString();
        Log.i(TAG,"====request body==== " + jsonBody);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                jsonBody);
        Log.i(TAG,"444444444444444444");
        final Request request = new Request.Builder()
                .url(face_detect_host + face_detect_url)
                .post(requestBody)
                .build();
        Log.d(TAG,"Request = " + request.url());
        Log.d(TAG,"Request = " + request.headers().toString());
        Log.d(TAG,"#######################");
        try {
            Response response=client.newCall(request).execute();
            String bodyResult = response.body().string();
            userResponse.statusCode=response.code();
            JSONObject bodyJson = JSON.parseObject(bodyResult);
            Log.d(TAG,"====body===" + bodyResult);
            userResponse.body=bodyJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG,"face detect request out ...");

        return userResponse;
    }




    /**
     *  人脸检测
     * */
    public void face_detect(Callback callback) throws Exception {
        Log.d(TAG,"face detect request in ...");
        OkHttpClient client = getAuthorizationClient();
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("deviceId", AppConstants.UHOME_DEVICEID);
        requestParam.put("faceData", Base64Util.encodeBase64File(Base64Util.DEFAULT_COMPRESSED_FILE_PATH));
        requestParam.put("width", 640);
        requestParam.put("height", 1080);
        String jsonBody = new JSONObject(requestParam).toJSONString();
        Log.i(TAG,"====request body==== " + jsonBody);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                jsonBody);
        final Request request = new Request.Builder()
                .url(face_detect_host + face_detect_url)
                .post(requestBody)
                .build();
        try {
            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG,"face detect request out ...");

    }


    private String getSign() {
        return Sign(AppConstants.UHOME_APP_ID, AppConstants.UHOME_APP_KEY, AppConstants.UHOME_CLIENT_ID);
    }

    // clientId，客户端ID，主要⽤途为唯⼀标识客户端 (例如,⼿机)。可调⽤usdk得到客户端ID的值
    private  String Sign(String appId, String appKey, String client_id) {
        appKey = appKey.trim();
        appKey = appKey.replaceAll("\"", "");
        StringBuffer sb = new StringBuffer();
        sb.append(appId).append(appKey).append(client_id);
        MessageDigest md = null;
        byte[] bytes = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            bytes = md.digest(sb.toString().getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return BinaryToHexString(bytes);
    }

    private String BinaryToHexString(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        String hexStr = "0123456789abcdef";
        for (int i = 0; i < bytes.length; i++) {
            hex.append(String.valueOf(hexStr.charAt((bytes[i] & 0xF0) >> 4)));
            hex.append(String.valueOf(hexStr.charAt(bytes[i] & 0x0F)));
        }
        return hex.toString();
    }








}
